package com.norrielm.GooglePlusPosts.service;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import android.util.Log;

/**
 * Receiver of profile changes.
 * 
 * @author Lauren Norrie (norrielm)
 */
public class ServerReceiver {

	public static final int MSG_UPDATE = 1;
	public static final String ACTION_STARTED = "ProfileReceiver.STARTED";
	public static final String ACTION_UPDATE = "ProfileReceiver.UPDATE";
	public static final String ACTION_STOPPED = "ProfileReceiver.STOPPED";
	public static final String TEST_ID = "100484754486751513084"; // CompSoc 
	public static String HOST = "10.10.10.13"; 
	public static int PORT = 1234;
	
	private static final String LOG = "GooglePlusPosts";
	private boolean exiting = false;
	private String profileId;
	
	private Runnable receive = new Runnable() {
		@Override public void run() {
			while (!exiting) {
				receiveFromServer();
				Log.d(LOG, "Profile Id now " + profileId);
			}
		}
	};
	
	public ServerReceiver() {
		new Thread(receive).start();
	}
	
	private String receiveFromServer() {
		try {
			DatagramSocket socket = new DatagramSocket();
			byte[] buf = new byte[1024];
			DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName(HOST), 
				PORT);
			Log.d(LOG, "Waiting to receive on " +  HOST + ":" + PORT);
			socket.receive(packet);
			Log.d(LOG, "Received message " +  packet.getData().toString().trim());
			profileId = packet.getData().toString().trim();
		} catch (Exception e) {
			// Ignoring errors for now.
			Log.e(LOG, "Failed to receive message " + e.getMessage());
		}
		Log.e(LOG, "Sending Id " + profileId);
		return profileId;
	}

	public void stop() {
		exiting = true;
	}
}
